export default {
    name: "muimgpicker",
    props: {
        modelValue: {
            type: Array,
            default: () => []
        },
        uploadurl: {
            type: String,
            default: () => window.APP_CONFIG?.baseurl + 'v1/dbupload'
        },
    },

	setup(props, {emit}) {
	    const { smartSpeak } = inject('speech'); //语音
		const dialogVisible = ref(false);
		const imageList = ref([]);
		const loading = ref(false);
		const currentPage = ref(1);
		const pageSize = ref(12);
		const total = ref(0);
		const noMore = ref(false);
		const fileInput = ref(null);
		const baseurl = window.APP_CONFIG.baseurl;
        const currentFolder = ref('blog');
        const folderList = ref({blog: '公告', bjt: '背景图', ico: '图标', template: '网页模板', sc: '素材',});
        
        // 选择文件夹
        const onFolderChange = () => {
            currentPage.value = 1;
            total.value = 0;
            noMore.value = false;
            imageList.value = [];
            debounceLoad();
        };

		const loadImages = async () => {
			if (loading.value || noMore.value) return
			loading.value = true
			const res = await getimglist({page: currentPage.value, pageSize: pageSize.value, folder: currentFolder.value});
			const newList = res.items.map(item => ({
				id: item.id,
				url: item.url.startsWith('http') ? item.url : `${baseurl}${item.url}`
			}))
			imageList.value = currentPage.value === 1 ? newList : [...imageList.value, ...newList];
			total.value = res.total
			noMore.value = imageList.value.length >= res.total;
			currentPage.value++;
			loading.value = false;
		}
		
		const debounceLoad = _.debounce(loadImages, 100);

		const showPicker = () => {
			dialogVisible.value = true
			if (imageList.value.length === 0) debounceLoad()
		}

		const closePicker = () => {
			dialogVisible.value = false
		}

		const handleDelete = () => {
			emit('update:modelValue', '')
		}
		
		const triggerUpload = () => {
		    if(!currentFolder.value) return ElMessage.error('文件夹不得为空');
			fileInput.value.click()
		}
			
        const handleSelect = (item) => {
            const newValue = [...props.modelValue];
            // 添加/移除选中逻辑
            const index = newValue.findIndex(url => url === item.url);
            if (index === -1) {
                newValue.push(item.url);
            } else {
                newValue.splice(index, 1);
            }
            emit('update:modelValue', newValue);
        };
        
		const handleFileChange = async (e) => {
			const file = e.target.files[0]
			if (!file) return
			if (file.size > 10 * 1024 * 1024) {
				return ElMessage.error('图片大小不能超过10M')
			}
			if(!currentFolder.value) return ElMessage.error('文件夹不得为空');
			const formData = new FormData()
			formData.append('file', file)
			formData.append('name', 'file')
			formData.append('path', currentFolder.value); // 添加文件夹参数
			try {
				const response = await axios.post(props.uploadurl, formData, {
					headers: {
						'Content-Type': 'multipart/form-data'
					}
				})
				const newImage = {
					id: response.data.data.id,
					url: response.data.data.url || ''
				}
				imageList.value.unshift(newImage)
                if (response.data.data.url) {
                    const newArr = [...props.modelValue, response.data.data.url];
                    emit('update:modelValue', newArr);
                }
			} catch (error) {
				ElMessage.error('上传失败')
			} finally {
				e.target.value = ''
			}
		}
        
        const deleteImage = async (item) => {
            try {
                await ElMessageBox.confirm('确定要永久删除这张图片吗？', '确认删除', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                await deleteimg(item);
                // 更新图片列表
                imageList.value = imageList.value.filter(i => i.id !== item.id);
                // 更新modelValue（如果包含被删除的url）
                const newValue = props.modelValue.filter(url => url !== item.url);
                emit('update:modelValue', newValue);
            } catch (error) {
                // 取消删除不处理
            }
        }

        // 新增单个删除方法
        const handleDeleteOne = (index) => {
            const newValue = [...props.modelValue];
            newValue.splice(index, 1);
            emit('update:modelValue', newValue);
        };
        
		const loadMore = () => {
			if (!loading.value && !noMore.value) debounceLoad()
		}

        return {
            dialogVisible,
            imageList,
            loading,
            currentPage,
            pageSize,
            total,
            noMore,
            fileInput,
            baseurl,
            loadImages,
            showPicker,
            closePicker,
            handleDelete,
            handleSelect,
            triggerUpload,
            handleFileChange,
            deleteImage,
            loadMore,
            handleDeleteOne,
            currentFolder,
            folderList,
            onFolderChange,
            debounceLoad
        };
    },
    
    template: `
        <div class="single-image-picker">
            <el-scrollbar height="800px">
                <div @click="showPicker" style="min-height: 100%;display: flex;flex-wrap: wrap;align-content: flex-start;padding: 10px;box-sizing: border-box;">
                    <!-- 多图预览 -->
                    <div v-for="(url, index) in modelValue" :key="index" class="preview-content" style="width:200px; height:auto;">
                        <img :src="url" style="width:200px;height:auto;" />
                        <el-icon style="delete-btn" @click.stop="handleDeleteOne(index)">
                            <Delete />
                        </el-icon>
                    </div>
                    <!-- 上传触发按钮 -->
                    <div v-if="modelValue.length === 0" class="upload-trigger" style="width:200px;height:200px;border: 2px dashed #e5e5e5;border-radius: 8px;background: #f8f8f8;">
                        <el-icon class="camera-icon"><Camera /></el-icon>
                        <span class="tip-text">点击选择图片</span>
                    </div>
                </div>
            </el-scrollbar>

            <!-- 弹窗内容 -->
            <el-dialog v-model="dialogVisible" custom-class="image-picker-dialog" :show-close="false">
            	<template #header>
                    <div class="dialog-header">
                    	<div class="header-left">
                            <span class="title">选择图片</span>
                            <div style="position: relative;width: 240px;">
                                <el-select v-model="currentFolder" placeholder="选择文件夹" @change="onFolderChange">
                                    <el-option v-for="(name, key) in folderList" :key="key" :label="name" :value="key"/>
                                </el-select>
                            </div>
                            	<el-button type="success" plain @click="triggerUpload">
                            		<el-icon><Upload /></el-icon><span>上传</span>
                            	</el-button>
                            </div>
                    	<el-icon class="close-icon" @click="closePicker">
                    		<Close />
                    	</el-icon>
                    </div>
            	</template>
            
            	<div v-infinite-scroll="loadMore" class="image-grid" :infinite-scroll-disabled="loading || noMore">
                    <div class="grid-container">
                    	<div v-for="item in imageList" :key="item.id" class="grid-item"	:class="{ selected: modelValue.includes(item.url) }" @click="handleSelect(item)">
                            <img :src="item.url" class="thumbnail" />
                            <div class="item-actions">
                                <div v-if="modelValue.includes(item.url)" class="selected-mark">
                            		<el-icon color="#fff"><Select /></el-icon>
                            	</div>
                            	<div class="delete-action" @click.stop="deleteImage(item)">
                            		<el-icon color="#fff">
                            			<Delete />
                            		</el-icon>
                            	</div>
                            </div>
                    	</div>
                    </div>
                    
                    <div v-if="loading" class="loading-text">加载中...</div>
                    <div v-if="noMore" class="loading-text">没有更多了</div>
            	</div>
            </el-dialog>
            
            <input ref="fileInput" type="file" accept="image/*" hidden @change="handleFileChange" />
        </div> 
    `   
}